package com.study.zookeeper.job;

import com.study.zookeeper.IZookeeperRegister;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 清理客戶端僵尸服务列表
 * Created by 张波 on 2020/6/21.
 */
@Slf4j
@Component
public class ClearRegisterJob implements CommandLineRunner {

    @Autowired
    private IZookeeperRegister zookeeperRegister;

    /**
     * 服务注册在zookeeper下的目录
     */
    @Value("${zookeeper.register.path:/server/register/path}")
    private String zookeeperRegisterPath;

    @Value("${zookeeper.client.register.path:client}")
    private String clientRegisterPath;

    @Override
    public void run(String... strings) throws Exception {
        while (true) {
            /*1、扫描服务端目录目录列表，获取对应服务的IP地址信息*/
            List<String> registerPathList = zookeeperRegister.getRegisterPathList(zookeeperRegisterPath);
            /*取得服务注册目录*/
            for (String path : registerPathList) {
                if (clientRegisterPath.equals(path)) {
                    /*说明为客户端注册目录，跳过*/
                    continue;
                }
                try {
                    /*取得注册的服务列表*/
                    List<String> registerServiceList = zookeeperRegister.getRegisterPathList(path);
                    log.info("从目录：{}，获取得服务注册列表包括：{}", zookeeperRegisterPath + "/" + path, registerServiceList);
                    /*取得客户注册目录下的服务列表*/
                    List<String> registerClientList = zookeeperRegister.getRegisterPathList(clientRegisterPath + "/" + path);
                    log.info("从目录：{}，获取得服务注册列表包括：{}", zookeeperRegisterPath + "/" + clientRegisterPath + "/" + path, registerClientList);
                    if (null != registerClientList && !registerClientList.isEmpty()) {
                        for (String client : registerClientList) {
                            if (!registerServiceList.contains(client)) {
                                log.info("剔除无效服务列表：{}", zookeeperRegisterPath + "/" + clientRegisterPath + "/" + path + "/" + client);
                                zookeeperRegister.deleteRegisterPath(clientRegisterPath + "/" + path + "/" + client);
                            }
                        }
                    }
                } catch (Exception e) {
                    continue;
                }


            }
            TimeUnit.MINUTES.sleep(5);
        }


    }

}
